import 'dart:io';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:jet_rails/jr_app/jr_views/jr_discovery/jr_discovery_controller.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_app_bar.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_buttons.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_scaffold.dart';
import 'package:jet_rails/jr_utils/jr_toast.dart';

class JrArticlePostView extends StatefulWidget {
  const JrArticlePostView({super.key});

  @override
  State<JrArticlePostView> createState() => _JrArticlePostViewState();
}

class _JrArticlePostViewState extends State<JrArticlePostView> {
  final controller = Get.find<JrDiscoveryController>();
  TextEditingController titleController = TextEditingController();
  TextEditingController contentController = TextEditingController();

  int maxTitleLength = 100;
  int maxContentLength = 500;

  @override
  void initState() {
    super.initState();
    Get.find<JrDiscoveryController>().postImageList.value.clear();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).unfocus();
      },
      child: JrScaffold(
        appBar: JrAppBar(
          title: 'Post article',
        ),
        body: SingleChildScrollView(
          physics: const ClampingScrollPhysics(),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                  margin: EdgeInsets.only(bottom: 18.h, left: 20.w, right: 20.w),
                  child: TextField(
                    decoration: InputDecoration(
                      labelText: 'Enter your title: ',
                      labelStyle: TextStyle(color: Colors.white, fontSize: 16.r),
                      focusedBorder: const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.white),
                      ),
                      enabledBorder: const UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.white),
                      ),
                    ),
                    maxLines: 1,
                    style: TextStyle(color: Colors.white, fontSize: 16.r),
                    controller: titleController,
                    onChanged: (value) {
                      if (value.length >= maxTitleLength) {
                        titleController.text = value.substring(0, maxTitleLength);
                        titleController.selection =
                            TextSelection.fromPosition(TextPosition(offset: titleController.text.length));
                      }
                    },
                  )),
              Container(
                margin: EdgeInsets.only(bottom: 18.h, left: 20.w, right: 20.w),
                child: Stack(children: [
                  Container(
                      decoration: BoxDecoration(
                        gradient: const LinearGradient(
                            begin: Alignment.topLeft,
                            end: Alignment.bottomRight,
                            colors: [Color(0xFF693F73), Color(0xFF8F4D9A)]),
                        borderRadius: BorderRadius.circular(12.r),
                      ),
                      height: 200.h,
                      child: TextField(
                        decoration: const InputDecoration(
                            hintText: '', border: InputBorder.none, contentPadding: EdgeInsets.all(8)),
                        style: TextStyle(color: Colors.white60, fontSize: 16.r),
                        maxLines: 10,
                        controller: contentController,
                        onChanged: (value) {
                          if (value.length >= maxContentLength) {
                            contentController.text = value.substring(0, maxContentLength);
                            contentController.selection =
                                TextSelection.fromPosition(TextPosition(offset: contentController.text.length));
                            return;
                          }
                          Get.find<JrDiscoveryController>().postContentLength.value = value.length;
                        },
                      )),
                  Positioned(
                    right: 0,
                    bottom: 0,
                    child: Transform(
                      alignment: Alignment.center,
                      transform: Matrix4.rotationY(pi),
                      child: Image.asset('assets/images/icon_rails.png', height: 40.h),
                    ),
                  ),
                  Positioned(
                    right: 16,
                    bottom: 16,
                    child: Obx(() {
                      return Text(
                        '${controller.postContentLength.value}/$maxContentLength',
                        style: const TextStyle(color: Color(0x4D000000)),
                      );
                    }),
                  ),
                ]),
              ),
              buildImagePicker(),
              SizedBox(height: 110.h),
              Column(
                children: [
                  const SizedBox(width: double.infinity),
                  JrStyledButton(
                    width: 130,
                    text: 'Post',
                    onTap: () {
                      if (titleController.text.isEmpty) {
                        JrToast.show('Please input title.');
                        return;
                      }
                      if (contentController.text.isEmpty) {
                        JrToast.show('Please input content.');
                        return;
                      }
                      if (Get.find<JrDiscoveryController>().postImageList.isEmpty) {
                        JrToast.show('Please add image.');
                        return;
                      }
                      Get.find<JrDiscoveryController>().postArticle(
                        titleController.text,
                        contentController.text,
                      );
                    },
                  )
                ],
              )
            ],
          ),
        ),
      ),
    );
  }

  buildImagePicker() {
    Widget addWidget = GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () async {
        Get.find<JrDiscoveryController>().addPostImage();
      },
      child: Container(
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: const Color(0xFF3D3066),
          borderRadius: BorderRadius.circular(12.r),
        ),
        margin: EdgeInsets.only(top: 12.h, bottom: 32.h, left: 20.w, right: 20.w),
        width: 104.w,
        height: 110.h,
        child: SizedBox(
          width: 24.w,
          height: 20.h,
          child: SvgPicture.asset('assets/svg/icon_add_image.svg'),
        ),
      ),
    );

    return Obx(() {
      List<Widget> children = [];
      for (var item in Get.find<JrDiscoveryController>().postImageList) {
        children.add(Container(
          margin: EdgeInsets.only(top: 12.h, bottom: 32.h, left: 20.w, right: 0.w),
          child: Stack(children: [
            Container(
              width: 104.w,
              height: 110.h,
              clipBehavior: Clip.hardEdge,
              decoration: BoxDecoration(borderRadius: BorderRadius.circular(12.r)),
              child: Image.file(
                File(item),
                fit: BoxFit.fill,
              ),
            ),
            Positioned(
              right: 0,
              top: 0,
              child: GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  Get.find<JrDiscoveryController>().postImageList.value.remove(item);
                  Get.find<JrDiscoveryController>().postImageList.refresh();
                },
                child: Container(
                  width: 24.w,
                  height: 24.h,
                  decoration: BoxDecoration(
                      color: Colors.black54,
                      borderRadius:
                          BorderRadius.only(bottomLeft: Radius.circular(8.r), topRight: Radius.circular(12.r))),
                  child: Center(
                      child: Icon(
                    Icons.delete_forever_outlined,
                    size: 18.r,
                    color: Colors.white60,
                  )),
                ),
              ),
            ),
          ]),
        ));
      }

      if (children.length < 3) {
        children.add(addWidget);
      }
      return SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Row(
          children: children,
        ),
      );
    });
  }
}
